{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "977\n"
     ]
    }
   ],
   "source": [
    "import pandas as pd\n",
    "from sklearn.decomposition import LatentDirichletAllocation\n",
    "from sklearn.feature_extraction.text import TfidfVectorizer\n",
    "data = pd.read_csv(\n",
    "    'C:\\\\Users\\\\17914\\Desktop\\\\travelCF\\\\base\\\\data\\\\pois.csv')  # 读取景点和介绍\n",
    "\n",
    "# 景点数据\n",
    "places = []\n",
    "texts = [] \n",
    "\n",
    "for item in data['名称']: \n",
    "    places.append(item)\n",
    "\n",
    "for item in data['介绍']:\n",
    "    texts.append(item)\n",
    "print(len(texts))\n",
    "\n",
    "places[:] = places[:976]\n",
    "texts[:] = places[:976]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                          自然        文化        娱乐\n",
      "上海迪士尼度假区            6.406858  1.913388  1.679754\n",
      "东方明珠                1.679969  6.640214  1.679816\n",
      "外滩                  6.640654  1.679676  1.679670\n",
      "上海野生动物园             6.652122  1.673941  1.673938\n",
      "豫园                  1.671853  6.656352  1.671795\n",
      "...                      ...       ...       ...\n",
      "音乐童话经典舞台剧《冰雪女王》     1.396427  7.207328  1.396245\n",
      "快乐小孩儿童主题乐园          6.640654  1.679676  1.679670\n",
      "济阳公园                1.679969  6.640214  1.679816\n",
      "TaxiWay飞行中心(梅奔旗舰店)  7.070251  1.396596  1.533153\n",
      "贰叁叁脱口秀              1.679969  6.640214  1.679816\n",
      "\n",
      "[976 rows x 3 columns]\n"
     ]
    }
   ],
   "source": [
    "# TF-IDF特征提取\n",
    "vec = TfidfVectorizer()\n",
    "X = vec.fit_transform(texts)\n",
    "\n",
    "# LDA模型训练\n",
    "lda = LatentDirichletAllocation(n_components=3, random_state=0)\n",
    "lda.fit(X) \n",
    "\n",
    "# 获取每个景点对应主题的概率分布\n",
    "topic_weights = lda.transform(X)\n",
    "\n",
    "# 构建结果数据框\n",
    "scores = pd.DataFrame(topic_weights * 10 , \n",
    "                       index=places,\n",
    "                       columns=['自然','文化','娱乐'])\n",
    "print(scores)\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [],
   "source": [
    "scores.to_csv('ldaData.csv')"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
